<?php
//pc智能测评
namespace app\modules\cn\controllers;

use app\modules\content\models\Classes;
use yii;
use app\libs\Write;
use app\libs\IeltsController;
use app\modules\cn\models\ExerciseResult;
use app\modules\cn\models\MockAnswer;
use app\modules\test\models\TestAnswer;
use app\modules\test\models\TestList;
use app\modules\test\models\TestListDetail;
use app\modules\test\models\TestCate;
use app\modules\test\models\TestPublic;

class EvaluationController extends IeltsController
{

    public $enableCsrfValidation = false;
    public $layout = 'cn';


    //获取所有的试卷
    public function actionGetPaper()
    {
        $uid = Yii::$app->session->get('uid');
        $paper = TestCate::find()->asArray()->where("pid=0")->all();
        foreach ($paper as $k => $v) {
            $paper[$k]['son'] = TestCate::find()->where('pid=' . $v['id'])->asArray()->all();
            if ($uid == false) {
                $paper[$k]['pubId'] = '';
                continue;
            }
            $pubData = TestPublic::find()->asArray()->where('uid=' . $uid . ' and cateId=' . $v['id'] . ' and status=1')->orderBy('id desc')->one();
            if ($pubData != false) {
                $paper[$k]['pubId'] = ($pubData['createTime'] > time() - 432000) ? $pubData['id'] : '';
            } else {
                $paper[$k]['pubId'] = '';
            }
        }
        return $this->render('paper', ['paper' => $paper]);
    }

    //获取试卷的各部分信息
    public function actionGetSubject()
    {
        $paperId = \Yii::$app->request->get('paperId');
        $uid = Yii::$app->session->get('uid');
        if (!is_numeric($paperId)) {
            die('<script>alert("请求错误！");history.go(-1);</script>');
        }
        if ($uid == false) {
            header('Location:https://www.thinkuprep.com/login.html?source=10&url=http://www.thinkuprep.com/evaluation/notice.html?paperId=' . $paperId);
            exit;
        }
        $subject = TestCate::find()->asArray()->where("pid=$paperId")->all();
        $paper = TestCate::find()->asArray()->where("id=$paperId")->one();
        $totalTime = array_sum(array_column($subject, 'time'));
        return $this->renderPartial('notice', ['subject' => $subject, 'totalTime' => $totalTime, 'paper' => $paper]);
    }

    //用户选择做题的部分
    public function actionChoiceSubject()
    {
        $subjectId = \Yii::$app->request->post('subjectId');
        $cateId = \Yii::$app->request->post('cateId');//试卷的id
        $uid = Yii::$app->session->get('uid');
        if ($uid == false) {
            die(json_encode(['code' => 0, 'message' => '未登录!']));
        }
        $model = new TestPublic();
        $model->cateId = $cateId;
        $model->subjectId = $subjectId;
        $model->uid = $uid;
        $model->startTime = time();
        $model->status = 0;
        $model->createTime = time();
        $re = $model->save();
        if ($re != false) {
            $pubData = TestPublic::find()->asArray()->where('uid=' . $uid)->orderBy('id desc')->one();
            die(json_encode(['code' => 1, 'data' => ['pubId' => $pubData['id'], 'subjectId' => explode(',', $pubData['subjectId'])], 'message' => '请求成功!']));
        } else {
            die(json_encode(['code' => 0, 'data' => '', 'message' => '请求成功!']));
        }
    }

    //取题
    public function actionGetQuestion()
    {
        $subjectId = \Yii::$app->request->get('subjectId');
        $pubId = \Yii::$app->request->get('pubId');
        if (!is_numeric($subjectId) || !is_numeric($pubId)) {
            die('<script>alert("请求错误！");history.go(-1);</script>');
        }
        $uid = \Yii::$app->session->get('uid');
        $pubData = TestPublic::find()->select('subjectId,time')->asArray()->where('id=' . $pubId)->orderBy('id desc')->one();
        $listData = TestList::find()->asArray()->where('subjectId =' . $subjectId)->orderBy('id asc')->all();
        $key = array_search($subjectId, explode(',', $pubData['subjectId'])) !== '' ? array_search($subjectId, explode(',', $pubData['subjectId'])) + 1 : '';
        $nextSubject = isset(explode(',', $pubData['subjectId'])[$key]) ? explode(',', $pubData['subjectId'])[$key] : '';
        $nextType = '';
        if ($nextSubject != false) {
            $cate = TestCate::find()->asArray()->where('id=' . $nextSubject)->one();
            $nextType = $cate['type'] != false ? $cate['type'] : '';
        }
        $preSubject = isset(explode(',', $pubData['subjectId'])[$key - 2]) ? explode(',', $pubData['subjectId'])[$key - 2] : '';
        $preType = '';
        if ($preSubject != false) {
            $cate = TestCate::find()->asArray()->where('id=' . $preSubject)->one();
            $preType = $cate['type'] != false ? $cate['type'] : '';
        }
        static $data = array();
        foreach ($listData as $k => $v) {
            $data[$k]['parent'] = $v;
            $cateData = TestCate::find()->asArray()->where('id=' . $v['subjectId'])->one();
            $data[$k]['parent']['type'] = $cateData['type'];
            $data[$k]['son'] = TestListDetail::find()->asArray()->where('pid=' . $v['id'])->all();
            foreach ($data[$k]['son'] as $ke => $val) {
                $data[$k]['son'][$ke]['option'] = $val['option'] != false ? explode('<br />', str_replace(PHP_EOL, '', nl2br($val['option']))) : '';
                $answer = TestAnswer::find()->asArray()->where('question_id=' . $val['id'] . ' and pub_id=' . $pubId . ' and uid=' . $uid)->one();
                $data[$k]['son'][$ke]['userAnswer'] = $answer != false ? $answer['answer'] : '';
                $data[$k]['son'][$ke]['remark'] = $answer != false ? $answer['remark'] : '';
                if ($subjectId == 22 || $subjectId == 23) {
                    $data[$k]['son'][$ke]['noSignArticle'] = strip_tags(html_entity_decode(str_replace([PHP_EOL, '&nbsp;', ':'], ' ', $val['article'])));
                    if ($subjectId == 22) {
                        $data[$k]['son'][$ke]['spokenTime'] = $ke == 0 ? 30 : 150;
                    } else {
                        $data[$k]['son'][$ke]['spokenTime'] = $ke == 0 ? 30 : ($ke == 1 ? 120 : 40);
                    }
                }
            }
            $data[$k]['parent']['option'] = $v['option'] != false ? explode('<br />', str_replace(PHP_EOL, '', nl2br($v['option']))) : '';
        }
        $cateData = TestCate::find()->select('x2_test_cate.*,pc.name as pidName')->asArray()->leftJoin('x2_test_cate as pc', 'x2_test_cate.pid=pc.id')->where('x2_test_cate.id=' . $subjectId)->one();
        $totalTime = $cateData['time'] != false ? $cateData['time'] : '';
        $time = json_decode($pubData['time'], true);
        if ($cateData['type'] == 1) {
            $view = 'question';//词汇
        } elseif ($cateData['type'] == 2) {
            $view = 'read';//阅读
        } elseif ($cateData['type'] == 3) {
            $view = 'listen';//听力
        } elseif ($cateData['type'] == 4) {
            $view = 'write';//写作
        } elseif ($cateData['type'] == 5 || $cateData['type'] == 7) {
            $view = 'translate';//翻译
        } elseif ($cateData['type'] == 6) {
            $view = 'word';//单词
        } else {
            $view = 'speak';//口语
        }
//        var_dump($cateData['type']);
//        var_dump($data);die;
        return $this->renderPartial($view, ['list' => $data, 'pubId' => $pubId, 'nextSubject' => $nextSubject, 'nextType' => $nextType, 'preSubject' => $preSubject, 'preType' => $preType, 'time' => isset($time[$subjectId]) ? $time[$subjectId] : 0, 'totalTime' => $totalTime, 'cateData' => $cateData]);
    }

    /**
     * @Title  保存答案
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionSaveAnswer()
    {
        //判分 保存结果
        $uid = Yii::$app->session->get('uid');
        $pubId = Yii::$app->request->post('pubId');
        $content = json_decode(Yii::$app->request->post('content'), true);//答案的json包括 id answer trueAnswer type
        $time = Yii::$app->request->post('time');
        $subjectId = Yii::$app->request->post('subjectId');
//        $content = [['id' => 2, 'answer' => 'D', 'trueAnswer' => 'D', 'type' => 2,'remark'=>'']];
        $pubData = TestPublic::find()->asArray()->where('id=' . $pubId)->one();
        if ($uid == false) {
            die(json_encode(['message' => '未登录', 'code' => 0]));
        }
        foreach ($content as $k => $v) {
            $insert['question_id'] = $v['id'];//小题的id
            $insert['pub_id'] = $pubId;//同一次做题的id
            $insert['answer'] = $answer = htmlspecialchars($v['answer']);//用户答案
            $insert['really'] = $really = $v['trueAnswer'];//正确答案
            $insert['uid'] = $uid;
            $insert['createtime'] = time();
            $insert['source'] = 2;
            if ($v['type'] == 4) {//写作
                $remark = Write::writeCorrect($insert['answer'], 1, 'ielts');
                $res = json_decode($remark, true);
                if ($res['errorCode'] == 0) {
                    $insert['remark'] = json_encode($res['Result']);
                    $insert['score'] = $res['Result']['totalScore'];//总分
                } else {
                    die(json_encode(['message' => '写作批改出错', 'code' => 0]));
                }
            } elseif ($v['type'] == 8 || $v['type'] == 9) {//口语智能批改,保存结果
                $insert['remark'] = $v['remark'];
                $insert['score'] = json_decode($v['remark'], true)['total_score'];//总分
            } elseif ($v['type'] == 5 || $v['type'] == 7) {//翻译不判断对错或者评分
                $insert['remark'] = $v['remark'];
                $insert['score'] = '';
            } else {//单词 词汇 多选 单选 填空
                $answer = strtolower(ExerciseResult::romanNumber(trim($answer)));
                $really = strtolower(ExerciseResult::romanNumber(trim($really)));
                $insert['result'] = MockAnswer::checkAnswer($answer, $really);
                $insert['remark'] = '';
            }
            $sign = TestAnswer::find()->asArray()->where("question_id=" . $v['id'] . " and uid=$uid and pub_id=$pubId ")->one();
            if ($sign) {
                $re = TestAnswer::updateAll(['answer' => $insert['answer'], 'result' => $insert['result'], 'score' => $insert['score'], 'remark' => $insert['remark']], "uid=$uid and pub_id=$pubId and question_id=" . $v['id']);
            } else {
                $re = Yii::$app->db->createCommand()->insert("{{%test_answer}}", $insert)->execute();

            }
        }
        $pubData['time'] = json_decode($pubData['time'], true);
        $pubData['time'][$subjectId] = $time;
        TestPublic::updateAll(['time' => json_encode($pubData['time'])], 'id=' . $pubId);
        die(json_encode(['message' => '保存成功', 'code' => 1]));
    }

    /**
     * @Title  查看结果
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionResult()
    {
        //判分 保存结果
        $pubId = Yii::$app->request->get('pubId');
        if (!is_numeric($pubId)) {
            die('<script>alert("请求错误！");history.go(-1);</script>');
        }
        $pubData = TestPublic::find()->asArray()->where('id=' . $pubId)->one();
        if ($pubData['status'] != 1) {
            TestPublic::updateAll(['status' => 1, 'endTime' => time()], 'id=' . $pubId);
            $pubData = TestPublic::find()->asArray()->where('id=' . $pubId)->one();
        }
        $data = TestAnswer::getTestDetail($pubData);
        if ($pubData['score'] == false) TestPublic::updateAll(['score' => $data['score']], 'id=' . $pubId);
        $class = Classes::find()->where("isTop=1")->asArray()->limit(3)->orderBy('sort asc,id desc')->all();
        $userData = Yii::$app->session->get('userData');
        $avgtime=TestPublic::getAvgTime($pubData);
        return $this->render('result', ['data' => $data, 'class' => $class, 'userData' => $userData,'avgTime'=>$avgtime]);
    }

    /**
     * @Title  答题卡
     * @Author yoyo
     * @Date   2023-05-07
     */
    public function actionAnswerSheet()
    {
        $pubId = \Yii::$app->request->get('pubId');
        if (!is_numeric($pubId)) {
            die(json_encode(['code' => 0, 'message' => '请求错误!']));
        }
        $uid = \Yii::$app->session->get('uid');
        $pubData = TestPublic::find()->select('subjectId,time')->asArray()->where('id=' . $pubId)->orderBy('id desc')->one();
        $subject = explode(',', $pubData['subjectId']);
        static $data = array();
        foreach ($subject as $key => $value) {
            $listData = TestList::find()->asArray()->where('subjectId =' . $value)->orderBy('id asc')->all();
            foreach ($listData as $k => $v) {
                $data[$key]['data'][$k]['parent'] = $v;
                $cateData = TestCate::find()->asArray()->where('id=' . $v['subjectId'])->one();
                $data[$key]['data'][$k]['parent']['type'] = $cateData['type'];
                $data[$key]['data'][$k]['son'] = TestListDetail::find()->asArray()->where('pid=' . $v['id'])->all();
                foreach ($data[$key]['data'][$k]['son'] as $ke => $val) {
                    $answer = TestAnswer::find()->asArray()->where('question_id=' . $val['id'] . ' and pub_id=' . $pubId . ' and uid=' . $uid)->one();
                    $data[$key]['data'][$k]['son'][$ke]['userAnswer'] = $answer != false ? $answer['answer'] : '';
                    $data[$key]['data'][$k]['son'][$ke]['questionType'] = $v['questionType'];
                }
                $data[$key]['type'] = $cateData['type'];
            }
            $time = json_decode($pubData['time'], true);
            $data[$key]['time'] = isset($time[$value]) ? $time[$value] : 0;
        }
        die(json_encode(['code' => 1, 'data' => ['list' => $data, 'pubId' => $pubId], 'message' => '请求成功!']));
    }

    /**
     * 上传语音的做题数据
     * by  yoyo
     */
    public function actionUpSpokenAudio()
    {
        if (empty($_FILES['file'])) {
            die(json_encode(['code' => 0, 'message' => '文件不能为空!']));
        }
        $file = $_FILES['file'];
        $uid = Yii::$app->session->get('uid');
        if ($uid == false) {
            $re = ['code' => 2, 'message' => '未登录'];
            die(json_encode($re));
        }
        $upload = new \UploadFile();
//        $upload->int_max_size = 5240880;
//        $upload->arr_allow_exts = array('mp3');
        $upload->int_max_size = 20145728;
        $upload->arr_allow_exts = array('mp3', 'ogg', 'wav');
        $upload->str_save_path = Yii::$app->params['upSpoken'];
        if (Yii::$app->request->post('client') == 'html5') {
            $file['name'] = Yii::$app->request->post('filename');
        }
        $arr_rs = $upload->upload($file);
        if ($arr_rs['int_code'] == 1) {
            $filePath = '/' . Yii::$app->params['upSpoken'] . $arr_rs['arr_data']['arr_data'][0]['savename'];
            $res['code'] = 1;
            $res['message'] = '上传成功';
            $res['file'] = $filePath;
        } else {
            $res['code'] = 0;
            $res['message'] = '上传失败，请重试';
        }
        die(json_encode($res));

    }
}
